package reflection;

import java.lang.annotation.*;
import java.lang.reflect.Field;

/**
 * @author 小小唐
 * @Date 2022/9/12-星期一-15:15
 *
 * 反射操作注解 ORM
 */
public class Demo11 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        //通过反射获得对象
        Class c1 = Class.forName("reflection.Student1");

        //通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println("获得的类注解:"+annotation);
        }

        //获得注解的value值
        TableTang tableTang = (TableTang) c1.getAnnotation(TableTang.class);
        String value = tableTang.value();
        System.out.println("value的指定值:"+value);

        //获得类指定的注解
        Field f = c1.getDeclaredField("name");
        FieldTang annotation = f.getAnnotation(FieldTang.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());

    }

}

@TableTang("db_students")
class Student1{
    @FieldTang(columnName = "db_id",type = "int",length = 10)
    private int id;
    @FieldTang(columnName = "db_name",type = "varchar",length = 4)
    private String name;
    @FieldTang(columnName = "db_password",type = "varchar",length = 10)
    private String password;

    public Student1() {
    }

    public Student1(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "Student1{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableTang{
    String value();
}

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldTang{
    String columnName();
    String type();
    int length();
}